package com.yfp.group.service.impl;

import com.yfp.common.core.exception.ServiceException;
import com.yfp.group.config.WxMpConfiguration;
import com.yfp.group.config.WxMpProperties;
import com.yfp.group.service.WxUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxUserServiceImpl implements WxUserService {

    @Resource
    private WxMpProperties properties;

    @Resource
    private WxMpConfiguration wxMpConfiguration;

    @Override
    public String appIdInfo() {
        return properties.getConfigs().get(0).getAppId();
    }

    @Override
    public Map<String, Object> userInfo(String wxCode) {
        log.info("获取用户的openId,wxCode:{}", wxCode);
        WxMpService wxMpService = null;
        WxOAuth2AccessToken wxOAuth2AccessToken = null;
        try {
            wxMpService = wxMpConfiguration.wxMpService();
            wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(wxCode);
        } catch (WxErrorException e) {
            log.error("获取openId失败", e);
            throw new ServiceException("获取openId失败:" + e.getError().getErrorMsg());
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("openId", wxOAuth2AccessToken.getOpenId());
        resultMap.put("unionId", wxOAuth2AccessToken.getUnionId());
        return resultMap;
    }
}
